package com.xuecheng.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.AddCourseResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.domain.course.response.CoursePublishResult;
import com.xuecheng.framework.domain.course.response.CourseView;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.client.CmsPageClient;
import com.xuecheng.manage_course.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by Aniymx on 2018/12/26 21:56.
 */
@Service
public class CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private TeachplanRepository teachplanRepository;
    @Autowired
    private CourseBaseRepository courseBaseRepository;
    @Autowired
    private CourseMarketRepository courseMarketRepository;

    @Autowired
    private CoursePicRepository coursePicRepository;

    @Autowired
    private CmsPageClient cmsPageClient;

    @Autowired
    private CoursePubRepository coursePubRepository;

    @Autowired
    private TeachplanMediaRepository teachplanMediaRepository;
    @Autowired
    private TeachplanMediaPubRepository teachplanMediaPubRepository;


    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;


    /**
     * @Description: 查询当前课程的课程计划
     * @Param:
     * @return:
     * @Author: Mr.aniymx
     * @Date:
     */
    public TeachplanNode selectList(String courseId) {
        return courseMapper.selectList(courseId);
    }

    /**
     * @Description: 为当前课程添加课程的计划
     * @Param:
     * @return:
     * @Author: Mr.aniymx
     * @Date:
     */
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan) {
//取出courseId,根据courseId进行查询是不是父级节点,如果是就设置级别为一级,不是就设置0级
        // System.out.println(teachplan);
        if (teachplan == null ||
                StringUtils.isEmpty(teachplan.getCourseid()) ||
                StringUtils.isEmpty(teachplan.getPname())) {
            ExceptionCast.cast(CommonCode.INVALIDPARAM);
        }
        //取出父节点
        String parentId = teachplan.getParentid();
        if (StringUtils.isEmpty(parentId)) {
            //如果没有创建课程根节点
            parentId = this.getTeachplanRoot(teachplan.getCourseid());
        }
        //根据parentId 取出数据
        Optional<Teachplan> optional = teachplanRepository.findById(parentId);
        if (!optional.isPresent()) {
            ExceptionCast.cast(CommonCode.INVALIDPARAM);
        }
        //得到父级节点
        Teachplan teachplanParent = optional.get();
        String parentGrade = teachplanParent.getGrade();
        teachplan.setParentid(parentId);
        teachplan.setStatus("0");
        //级别判断
        if (parentGrade.equals("1")) {
            parentGrade = "2";
        } else if (parentGrade.equals("2")) {
            parentGrade = "3";
        }
        teachplan.setGrade(parentGrade);
        Teachplan save = teachplanRepository.save(teachplan);
        System.out.println(save);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //获取根节点
    private String getTeachplanRoot(String courseId) {
        //校验课程id
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if (!optional.isPresent()) {
            return null;
        }
        //得到基本课程信息
        CourseBase courseBase = optional.get();
        //取出课程计划的根节点
        List<Teachplan> teachplanList = teachplanRepository.findByParentidAndCourseid("0", courseId);
        //如果没有数据,就进行数据的添加
        if (teachplanList == null || teachplanList.size() == 0) {
            Teachplan teachplan = new Teachplan();
            teachplan.setCourseid(courseId);
            teachplan.setParentid("0");
            teachplan.setGrade("1");//级别是1
            teachplan.setPname(courseBase.getName());
            teachplan.setStatus("0");//表示未发布
            teachplanRepository.save(teachplan);
        }
        Teachplan teachplan = teachplanList.get(0);
        //得到根节点id
        return teachplan.getId();
    }

    /**
     * @Description: 查询课程列表
     * @Param:
     * @return:
     * @Author: Mr.aniymx
     * @Date:
     */
    public QueryResponseResult findCourseList(String companyId, int page, int size, CourseListRequest courseListRequest) {
        if (courseListRequest == null) {
            courseListRequest = new CourseListRequest();
        }
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 7;
        }
        courseListRequest.setCompanyId(companyId);
        PageHelper.startPage(page, size);

        Page<CourseInfo> courseListPage = courseMapper.findCourseListPage(courseListRequest);
        List<CourseInfo> result = courseListPage.getResult();
        QueryResult<CourseInfo> courseBaseQueryResult = new QueryResult<>();

        courseBaseQueryResult.setList(result);
        courseBaseQueryResult.setTotal(courseListPage.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS, courseBaseQueryResult);
    }

    @Transactional
    public AddCourseResult addCourse(CourseBase courseBase) {
        courseBase.setStatus("202001");
        CourseBase save = courseBaseRepository.save(courseBase);
        AddCourseResult addCourseResult = new AddCourseResult(CommonCode.SUCCESS, save.getId());
        return addCourseResult;
    }

    /*根据id进行查询*/
    public CourseBase findById(String courseId) {
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseId);
        if (optionalCourseBase.isPresent()) {
            return optionalCourseBase.get();
        }
        return null;
    }

    /*更新课程信息*/
    public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
        CourseBase one = this.findById(id);
        if (one == null) {
            ExceptionCast.cast(CourseCode.COURSE_ISNULL);
        }
        //修改课程信息
        one.setName(courseBase.getName());
        one.setMt(courseBase.getMt());
        one.setSt(courseBase.getSt());
        one.setGrade(courseBase.getGrade());
        one.setStudymodel(courseBase.getStudymodel());
        one.setUsers(courseBase.getUsers());
        one.setDescription(courseBase.getDescription());
        CourseBase save = courseBaseRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /*获取课程营销信息*/
    public CourseMarket getCourseMarketById(String id) {
        Optional<CourseMarket> byId = courseMarketRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    /*
     * 更新课程营销信息
     * */
    public ResponseResult updateCourseMarket(String id, CourseMarket courseMarket) {
        //先进行查询
        CourseMarket one = this.getCourseMarketById(id);
        if (one != null) {
            //不为空进行更新
            one.setCharge(courseMarket.getCharge());
            one.setStartTime(courseMarket.getStartTime());//课程有效期，开始时间
            one.setEndTime(courseMarket.getEndTime());//课程有效期，结束时间
            String charge = courseMarket.getCharge();
            if (charge.equals("203001")) {
                float price = 0;
                one.setPrice_old(one.getPrice());
                one.setPrice(price);

            } else {
                one.setPrice_old(one.getPrice());
                one.setPrice(courseMarket.getPrice());
            }

            one.setQq(courseMarket.getQq());
            one.setValid(courseMarket.getValid());
            courseMarketRepository.save(one);
        } else {
            one = new CourseMarket();
            BeanUtils.copyProperties(courseMarket, one);
            one.setId(id);
            courseMarketRepository.save(one);
        }

        return new ResponseResult(CommonCode.SUCCESS);
    }

    /*添加课程图片*/
    public ResponseResult addCoursePic(String courseId, String pic) {
        CoursePic coursePic = coursePicRepository.findByCourseidAndPic(courseId, pic);
        if (coursePic != null) {
            return new ResponseResult(CourseCode.COURSEPIC_ISEXIT);
        }
        CoursePic newCoursePic = new CoursePic();
        newCoursePic.setCourseid(courseId);
        newCoursePic.setPic(pic);
        coursePicRepository.save(newCoursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /*查询课程图片列表*/
    /*查询出pic,从fastdfs进行下载图片*/
    public CoursePic findCoursePicList(String courseId) {
        CoursePic coursePic = coursePicRepository.findByCourseid(courseId);
        return coursePic;
    }

    /*删除课程图片*/
    @Transactional
    public ResponseResult deleteCoursePic(String courseId) {
        CoursePic coursePicList = this.findCoursePicList(courseId);
        if (coursePicList == null) {
            return new ResponseResult(CourseCode.COURSEPIC_ISNOTEXIT);
        }
        long l = coursePicRepository.deleteByCourseid(courseId);
        if (l > 0) {
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    /*获取课程的视图*/
    public CourseView getCourseView(String courseId) {
        CourseView courseView = new CourseView();
        Optional<CourseBase> courseBase = courseBaseRepository.findById(courseId);
        if (courseBase.isPresent()) {
            courseView.setCourseBase(courseBase.get());
        }
        CoursePic coursePic = coursePicRepository.findByCourseid(courseId);
        if (coursePic != null) {
            courseView.setCoursePic(coursePic);
        }
        CourseMarket courseMarketById = this.getCourseMarketById(courseId);
        if (courseMarketById != null) {
            courseView.setCourseMarket(courseMarketById);
        }
        TeachplanNode teachplanNode = courseMapper.selectList(courseId);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }

    /*远程调用cms,返回pageId拼接url路径*/
    public CoursePublishResult preview(String courseId) {
        CourseBase one = this.findById(courseId);
        //发布课程预览页面
        CmsPage cmsPage = new CmsPage();
        //站点
        cmsPage.setSiteId(publish_siteId);//课程预览站点
        //模板
        cmsPage.setTemplateId(publish_templateId);
        //页面名称
        cmsPage.setPageName(courseId + ".html");
        //页面别名
        cmsPage.setPageAliase(one.getName());
        //页面访问路径
        cmsPage.setPageWebPath(publish_page_webpath);
        //页面存储路径
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        //数据url
        cmsPage.setDataUrl(publish_dataUrlPre + courseId);
        //远程调用
        CmsPageResult cmsPageResult = cmsPageClient.save(cmsPage);
        if (!cmsPageResult.isSuccess()) {
            new CoursePublishResult(CommonCode.FAIL, null);
        }
        String pageId = cmsPageResult.getCmsPage().getPageId();

        String url = previewUrl + pageId;
        return new CoursePublishResult(CommonCode.SUCCESS, url);
    }

    /*课程发布*/
    @Transactional
    public CoursePublishResult publish(String courseId) {
        //构建coursepub
        CoursePub coursePub = this.createCoursePub(courseId);
        //将coursepub存到数据库
        CoursePub saveCoursePub = this.saveCoursePub(courseId, coursePub);
        CoursePub save = coursePubRepository.save(saveCoursePub);
        if (save == null) {
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_CREATE_INDEX_ERROR);
        }
//发布课程
        CmsPostPageResult cmsPostPageResult = this.publish_page(courseId);
        if (!cmsPostPageResult.isSuccess()) {
            ExceptionCast.cast(CommonCode.FAIL);
        }
        //保存媒资信息到TeachplanMediaPub,方便logstash抓取
        try {
            this.saveTeachplanMediaPub(courseId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String pageUrl = cmsPostPageResult.getPageUrl();

        //保存课程状态为已发布
        // this.saveCoursePubState(courseId);
        //保存课程的索引的信息
        //缓存课程的信息


        return new CoursePublishResult(CommonCode.SUCCESS, pageUrl);

    }

    //保存课程状态为已发布

    public CourseBase saveCoursePubState(String courseId) {
        CourseBase courseBase = this.findById(courseId);
        courseBase.setStatus("202002");
        CourseBase save = courseBaseRepository.save(courseBase);
        return save;
    }

    //发布课程正式页面
    public CmsPostPageResult publish_page(String courseId) {
        CourseBase one = this.findById(courseId);
        //发布课程预览页面
        CmsPage cmsPage = new CmsPage();
        //站点
        cmsPage.setSiteId(publish_siteId);//课程预览站点
        //模板
        cmsPage.setTemplateId(publish_templateId);
        //页面名称
        cmsPage.setPageName(courseId + ".html");
        //页面别名
        cmsPage.setPageAliase(one.getName());
        //页面访问路径
        cmsPage.setPageWebPath(publish_page_webpath);
        //页面存储路径
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        //数据url
        cmsPage.setDataUrl(publish_dataUrlPre + courseId);
        //发布页面
        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        return cmsPostPageResult;
    }

    //构建coursepub
    public CoursePub createCoursePub(String courseId) {
        CoursePub coursePub = new CoursePub();
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(courseId);
        if (courseBaseOptional.isPresent()) {
            BeanUtils.copyProperties(courseBaseOptional.get(), coursePub);
        }
        CoursePic coursePic = coursePicRepository.findByCourseid(courseId);
        if (coursePic != null) {
            BeanUtils.copyProperties(coursePic, coursePub);
        }
        Optional<CourseMarket> marketOptional = courseMarketRepository.findById(courseId);
        if (marketOptional.isPresent()) {
            BeanUtils.copyProperties(marketOptional.get(), coursePub);
        }
        TeachplanNode teachplanNode = courseMapper.selectList(courseId);
        String node = JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(node);
        return coursePub;
    }

    //存储coursepub到表coursepub
    public CoursePub saveCoursePub(String courseId, CoursePub coursePub) {
        if (StringUtils.isEmpty(courseId)) {
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CoursePub newCoursePub = null;
        Optional<CoursePub> optionalCoursePub = coursePubRepository.findById(courseId);
        if (optionalCoursePub.isPresent()) {
            newCoursePub = optionalCoursePub.get();
        }
        if (newCoursePub == null) {
            newCoursePub = new CoursePub();
        }
        BeanUtils.copyProperties(coursePub, newCoursePub);
        newCoursePub.setId(courseId);
        newCoursePub.setTimestamp(new Date());
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        String format = dateFormat.format(new Date());
        newCoursePub.setPubTime(format);
        return coursePub;
    }

    //保存媒资信息
    public ResponseResult savemedia(TeachplanMedia teachplanMedia) {
        if (teachplanMedia == null) {
            ExceptionCast.cast(CommonCode.INVALIDPARAM);
        }
        Optional<Teachplan> optional = teachplanRepository.findById(teachplanMedia.getTeachplanId());
        if (!optional.isPresent()) {
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_ISNULL);
        }
        Teachplan teachplan = optional.get();
        String grade = teachplan.getGrade();
        if (StringUtils.isEmpty(grade) || !grade.equals("3")) {
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_GRADEERROR);
        }
        Optional<TeachplanMedia> optionalTeachplanMedia = teachplanMediaRepository.findById(teachplan.getId());
        TeachplanMedia one = null;
        if (!optionalTeachplanMedia.isPresent()) {
            one = new TeachplanMedia();
        } else {
            one = optionalTeachplanMedia.get();
        }
//保存媒资信息与课程计划信息
        one.setTeachplanId(teachplan.getId());
        one.setCourseId(teachplanMedia.getCourseId());
        one.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
        one.setMediaId(teachplanMedia.getMediaId());
        one.setMediaUrl(teachplanMedia.getMediaUrl());
        teachplanMediaRepository.save(one);

        return new ResponseResult(CommonCode.SUCCESS);
    }

    //保存课程计划媒资信息

    public void saveTeachplanMediaPub(String courseId) {
        //查询课程媒资信息
        List<TeachplanMedia> teachplanMediaList = teachplanMediaRepository.findByCourseId(courseId);
        //将课程计划媒资信息存储待索引表
        teachplanMediaPubRepository.deleteByCourseId(courseId);
        List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();
        for (TeachplanMedia teachplanMedia : teachplanMediaList) {
            TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();
            BeanUtils.copyProperties(teachplanMedia, teachplanMediaPub);
            teachplanMediaPubList.add(teachplanMediaPub);
        }
        teachplanMediaPubRepository.saveAll(teachplanMediaPubList);
    }
}
